package net.sunofbeach.blog.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sunofbeach.blog.pojo.Image;
import net.sunofbeach.blog.pojo.User;
import net.sunofbeach.blog.pojo.query.ImageQuery;
import net.sunofbeach.blog.response.Result;
import net.sunofbeach.blog.response.ResultEnum;
import net.sunofbeach.blog.service.ImageService;
import net.sunofbeach.blog.service.UserService;
import net.sunofbeach.blog.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Bing
 * @since 2021-11-24
 */
@Api(tags = "上传图片")
@RestController
@RequestMapping("/admin/image")
public class ImageAdminApi {

    @Resource
    private UserService userService;

    @Resource
    private ImageService ImageService;

    /**
     * 上传图片
     * 一般来说，现在比较常用的是对象存储 一一> 很简单，看文档就可以学会
     * 使用 Nginx + fastDFS ==> fastDFS 一一》 处理文件上传，Nginx 一一》 负责处理文件访问（复杂）
     * 这里做最简单的上传到本地
     * MultipartFile file  单文件上传
     * MultipartFile[] file 数组为多文件上传
     *
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/{original}")
    public Result uploadImage(@PathVariable("original") String original, @RequestParam("file") MultipartFile file) {

        // 检验当前操作用户的身份
        User currentUser = userService.checkSobUser();
        if (currentUser == null) {
            // 账号未登录
            return Result.build(null, ResultEnum.ACCOUNT_NOT_LOGIN);
        }
        // 判断角色，拥有 role_admin 角色可以操作
        if (!Constants.User.ROLE_ADMIN.equals(currentUser.getRole())) {
            // 权限不足
            return Result.build(null, ResultEnum.PERMISSION_DENIED);
        }
        return ImageService.uploadImage(original, file);
    }


    @ApiOperation("获取图片")
    @PreAuthorize("@permission.admin()")
    @GetMapping("/{imageId}")
    public void getImage(HttpServletResponse response, @PathVariable("imageId") String imageId) {
        try {
            ImageService.viewImage(response, imageId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 图片列表
     *
     * @return
     */
    @ApiOperation("条件分页查询图片列表")
    @PreAuthorize("@permission.admin()")
    @GetMapping("/list/{page}/{size}")
    public Result listImage(@PathVariable("page") Long page, @PathVariable("size") Long size, ImageQuery query) {

        Page<Image> pageParam = new Page<>(page, size);
        IPage<Image> pageModel = ImageService.selectPage(pageParam, query);
        return Result.ok(pageModel);
    }


    /**
     * 逻辑删除
     * （修改状态值为0）
     *
     * @param imageId
     * @return
     */
    @ApiOperation("根据ID删除图片")
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    @DeleteMapping("/{imageId}")
    public Result deleteImage(@PathVariable("imageId") String imageId) {

        // 检验当前操作用户的身份
        User currentUser = userService.checkSobUser();
        if (currentUser == null) {
            // 账号未登录
            return Result.build(null, ResultEnum.ACCOUNT_NOT_LOGIN);
        }
        // 判断角色，拥有 role_admin 角色可以操作
        if (!Constants.User.ROLE_ADMIN.equals(currentUser.getRole())) {
            // 权限不足
            return Result.build(null, ResultEnum.PERMISSION_DENIED);
        }
        if (StringUtils.isEmpty(imageId)) {
            return Result.fail().message("图片ID不能为空");
        }
        Image imageFromDb = ImageService.getById(imageId);
        if (imageFromDb == null) {
            return Result.fail().message("该图片不存在");
        }
        imageFromDb.setState(Constants.Status.DELETE);
        boolean result = ImageService.updateById(imageFromDb);
        if (result) {
            return Result.ok().message("图片删除成功");
        }
        return Result.fail().message("图片删除失败");
    }


}

